﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Threading;
namespace SAICMOTOR
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow
    {

        DispatcherTimer _timer = new DispatcherTimer();
        DispatcherTimer _timerMonitor = new DispatcherTimer();
        private System.Drawing.Point _prePosition;
        [DllImport("User32.dll", EntryPoint = "FindWindow")]
        private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        private static extern int SendMessage(
        IntPtr hWnd,
        int msg,
        int wParam,
        int lParam
        );
        Process[] _processes = Process.GetProcesses();
        private bool _isMouseDown;

        public MainWindow()
        {
            InitializeComponent();
        }


        private void minBtn_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        private void closeBtn_Click(object sender, RoutedEventArgs e)
        {
            ConfirmExit();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            ConfirmExit();
            e.Cancel = true;
        }

        private static void ConfirmExit()
        {
            var result = MessageBox.Show("您确定关闭系统吗？", "提示信息", MessageBoxButton.OKCancel);
            if (result == MessageBoxResult.OK)
            {
                Environment.Exit(0);
            }
        }

        /// <summary>
        /// 根操作项名称，获取指定的属性值
        /// </summary>
        /// <param name="opName">操作项的名称</param>
        /// <param name="property">属性名</param>
        /// <returns>指定的属性的值</returns>
        private string GetConfig(string opName, string property)
        {
            var op = (IDictionary)ConfigurationSettings.GetConfig(opName);
            return op[property].ToString();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            tbOp1.Text = GetConfig("operation1", "text");
            tbOp1.Tag = GetConfig("operation1", "path");

            tbOp2.Text = GetConfig("operation2", "text");
            tbOp2.Tag = GetConfig("operation2", "path");

            tbOp3.Text = GetConfig("operation3", "text");
            tbOp3.Tag = GetConfig("operation3", "path");

            tbOp4.Text = GetConfig("operation4", "text");
            tbOp4.Tag = GetConfig("operation4", "path");

            tbOp5.Text = GetConfig("operation5", "text");
            tbOp5.Tag = GetConfig("operation5", "path");

            bd1.MouseUp += BtnClick;
            bd2.MouseUp += BtnClick;
            bd3.MouseUp += BtnClick;
            bd4.MouseUp += BtnClick;
            bd5.MouseUp += BtnClick;


            _timer.Interval = TimeSpan.FromSeconds(Convert.ToInt32(GetConfig("interval", "value")));
            _timer.Tick += delegate
            {
                KillNewerProcess();
            };
            _timer.Start();


            _timerMonitor.Interval = TimeSpan.FromSeconds(1);
            _timerMonitor.Tick += delegate
            {
                var currentPosition = System.Windows.Forms.Control.MousePosition;
                if (currentPosition.X != _prePosition.X || currentPosition.Y != _prePosition.Y)
                {
                    _timer.Stop();
                    _timer.Start();
                }
                _prePosition = currentPosition;
            };
            _timerMonitor.Start();
        }

        private void BtnClick(object sender, EventArgs e)
        {
            try
            {
                var textblock = ((Border)sender).Child as TextBlock;
                if (textblock == null) return;
                var path = textblock.Tag.ToString();
                Process.Start(new ProcessStartInfo(path));
            }
            catch (Win32Exception ex)
            {
                MessageBox.Show("指定的执行路径不正确!");
            }
            catch (Exception)
            {

            }

        }


        private void KillNewerProcess()
        {
            try
            {
                var processesNew = Process.GetProcesses();
                // if (_processes.Length == processesNew.Length) return;

                foreach (var item in processesNew)
                {
                    var flag = false; //在老线程集合中是否存在
                    foreach (var beforItem in _processes)
                    {
                        if (beforItem.Id == item.Id)
                        {
                            flag = true;
                            break;
                        }
                        ;
                    }
                    if (!flag)
                    {
                        if (!item.CloseMainWindow())
                        {
                            //关闭点击操作之后，新增的所有进程
                            item.Kill();
                        }
                    }
                }

                const int wmSyscommand = 0x0112;
                const int scClose = 0xF060;
                IntPtr wHandle;

                while ((wHandle = FindWindow("CabinetWClass", null)).ToInt32() > 0)
                {
                    SendMessage(wHandle, wmSyscommand, scClose, 0);
                }
                while ((wHandle = FindWindow("ExploreWClass", null)).ToInt32() > 0)
                {
                    SendMessage(wHandle, wmSyscommand, scClose, 0);
                }
            }
            catch (Exception)
            {
            }
            this.Activate();

        }

        private void maxBtn_Click(object sender, RoutedEventArgs e)
        {
            if (this.WindowState == WindowState.Maximized) this.WindowState = WindowState.Normal;
            else
            {
                this.WindowState = WindowState.Maximized;
            }
            _isMouseDown = false;
        }

        private void Window_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            var mousePosition = System.Windows.Forms.Control.MousePosition;
            _isMouseDown = true;
            var wdPositionX = this.Left;
            var wdPositionY = this.Top;
            difX = mousePosition.X - wdPositionX;
            difY = mousePosition.Y - wdPositionY;
        }

        private void Window_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            _isMouseDown = false;
        }

        private double difX, difY;
        private void Window_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (WindowState == WindowState.Normal && _isMouseDown)
            {

                var mousePosition = System.Windows.Forms.Control.MousePosition;

                Left = mousePosition.X - difX;
                Top = mousePosition.Y - difY;

            }
        }

        private void Window_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            maxBtn_Click(null, null);
        }

        private void Window_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            _isMouseDown = false;
        }
    }
}
